import json
import threading
import logging
logger = logging.getLogger(__name__)


def get_nested_value(dict_data, path_data):
    """
    dict_data dict 原始配置数据
    config_data str 获取的数据  以. 分隔 路径  以: 分隔默认值 以$开头的则去掉$ 符号
    返回 指定dict_data 指定的数据 
    """
    if isinstance(path_data, str):
        kk_path = path_data
        kk = kk_path.strip().split(":")
        defaut_vaule = None
        if len(kk) > 1:
            defaut_vaule = kk[1]
            kk_path = kk[0]
        if path_data.startswith('$'):
            kk_path = path_data[1:]  # 路径
        else:
            return path_data
            # 赋值 递归查找
        kk_paths = kk_path.strip().split(".")
        kk_value = dict_data
        # 取出值
        for ap in kk_paths:
            if isinstance(kk_value, list):
                if ap.isdigit() and (len(kk_value) > (int(ap))):
                    kk_value = kk_value[int(ap)]
                else:
                    logging.warning(
                        f"path is error path  {path_data}  ,date: {dict_data}  ")
                    kk_value = None
                    break
            elif isinstance(kk_value, dict):
                kk_value = kk_value.get(ap)
            else:
                logging.warning(
                    f"path is error path  {path_data}  ,date: {dict_data}  ")
                return defaut_vaule
        if kk_value == None:
            return defaut_vaule
        return kk_value


class ReadWriteLock:
    def __init__(self):
        pass

    def set_parameter_20230904(self, dict_data, data, other_config=None):
        if other_config is None:
            other_config = {}
        if isinstance(dict_data, dict):
            for dd in dict_data.keys():
                if isinstance(dict_data[dd], str):
                    if dict_data[dd].startswith('$'):  # 入参信息
                        dict_data[dd] = get_nested_value(data, dict_data[dd])

                    elif dict_data[dd].startswith('[$custom_info:'):  # 转存信息
                        k = dict_data[dd]

                        portrait_value = data['context_info'].custom_info.get(
                            k, None)
                        try:
                            if isinstance(portrait_value, str):
                                portrait_value1 = json.loads(portrait_value)
                                if isinstance(portrait_value1, dict) or isinstance(portrait_value1, list):
                                    portrait_value = portrait_value1
                        except ValueError:
                            portrait_value = data['context_info'].custom_info.get(
                                k, None)

                        dict_data[dd] = portrait_value
                    if isinstance(dict_data[dd], str):
                        if dict_data[dd] in other_config:
                            dict_data[dd] = other_config[dict_data[dd]]
                elif isinstance(dict_data[dd], dict):
                    self.__set_parameter(dict_data[dd], data, other_config)
        return dict_data


if __name__ == '__main__':
    rw_lock = ReadWriteLock()
    # 使用示例
    dict_data = {"context_info": "$context_info.context_info"}
    other_config = {}
    data = {"context_info": {
        "automata_traceroute": [
            "kb240627b2_nbsp_获取音量查询",
            "kb240627b2_nbsp_音量值回答",
            "kb240627b1_nbsp_获取区域清洁",
            "kb240627b1_nbsp_定制清洁命令"
        ],
        "bot_id": "c70dbafe-7c0d-4294-9af4-17fee6cf8a56",
        "chat_bot": "yiko_fld_zh_cn",
        "context_info": [
            {
                "in": {
                    "dm_transaction_id": "7df8c862-3b5d-4089-b27c-054583cbe986",
                    "from": "deebot",
                    "qtime": 1727000925.3384895,
                    "sentence": "event_wakeup_bypass",
                    "type": "event"
                },
                "out": {
                    "answer": {
                        "answer": "，",
                        "atime": 1727000925.6009216,
                        "audio": "",
                        "audio_id": "",
                        "available_inputs": [],
                        "callback": {},
                        "command": [],
                        "customize_msg": None,
                        "department_id": "553a10a8-317e-4630-87bf-314ab5352fa3",
                        "entities": [],
                        "group": "",
                        "instruction": "None",
                        "instruction_id": "656fe336489a6bc9579d3dce",
                        "intent": "event_wakeup_bypass",
                        "join_answer": [],
                        "knowledgebase": "kb230621b0",
                        "label": "event_wakeup_bypass",
                        "language": "zh-CN",
                        "listeningTime": -1,
                        "multiple_intents_replies": [],
                        "no_answer": False,
                        "offline": False,
                        "score": 2,
                        "send_to_client": False,
                        "sentence": "event_wakeup_bypass",
                        "sim_query": "event_wakeup_bypass",
                        "source": "intentqa",
                        "suggests": [],
                        "type": "business",
                        "voice": "."
                    }
                },
                "prep": {
                    "answer_type": [],
                    "confidence": {
                        "answer_type": 1,
                        "emo": 1,
                        "pro": 1,
                        "user_action": 1
                    },
                    "emo": [
                        "neutral"
                    ],
                    "keyword": [],
                    "ner": {
                        "HOTWORDS": [],
                        "SST": []
                    },
                    "pro": 1,
                    "sentence": "event_wakeup_bypass",
                    "tagword": [],
                    "user_action": [
                        "other"
                    ]
                }
            },
            {
                "in": {
                    "dm_transaction_id": "850784d0-54d4-42af-9668-13db5e1c847d",
                    "from": "deebot",
                    "qtime": 1727000929.3128724,
                    "sentence": "清扫沙发底",
                    "type": "text"
                },
                "out": {
                    "answer": {
                        "answer": "抱歉，未找到沙发，请向我描述一下它在什么位置",
                        "atime": 1727000929.735696,
                        "audio": "",
                        "audio_id": "",
                        "available_inputs": [],
                        "callback": {},
                        "command": [
                            {
                                "command_id": "deebot.no_area.to_clean",
                                "params": [
                                    {
                                        "domain": "no_area.to_clean",
                                        "intent": "no_area.to_clean",
                                        "slots": None,
                                        "space": [
                                            {
                                                "cleanmode": "X",
                                                "slot_type": "X",
                                                "text": "X ",
                                                "value": "X"
                                            }
                                        ]
                                    }
                                ],
                                "work_did": [
                                    "c70dbafe-7c0d-4294-9af4-17fee6cf8a56"
                                ]
                            }
                        ],
                        "customize_msg": None,
                        "department_id": "553a10a8-317e-4630-87bf-314ab5352fa3",
                        "entities": [
                            "沙发",
                            "清扫",
                            "底",
                            1
                        ],
                        "group": "",
                        "instruction": "获取区域清洁",
                        "instruction_id": "66e56511aae1ec2d9dc785e5",
                        "intent": "区域清洁_单扫",
                        "join_answer": [],
                        "knowledgebase": "kb240627b1",
                        "label": "",
                        "language": "zh-CN",
                        "listeningTime": 8,
                        "multiple_intents_replies": [],
                        "no_answer": False,
                        "offline": False,
                        "score": 1.9999912260000001,
                        "send_to_client": True,
                        "sentence": "清扫沙发底",
                        "sim_query": "区域清洁_单扫",
                        "source": "intentautomata",
                        "suggests": [],
                        "type": "business",
                        "voice": "抱歉，未找到沙发，请向我描述一下它在什么位置"
                    }
                },
                "prep": {
                    "answer_type": [
                        "其他"
                    ],
                    "confidence": {
                        "answer_type": 0.386244446,
                        "emo": 0.676222801,
                        "pro": 0.0940543711,
                        "user_action": 0.999975443
                    },
                    "emo": [
                        "neutral"
                    ],
                    "keyword": [
                        "清扫沙",
                        "发底"
                    ],
                    "ner": {
                        "ACTION": [
                            "清扫"
                        ],
                        "BOK": [],
                        "CITY": [],
                        "DGT": [],
                        "DIRECTION": [
                            "底"
                        ],
                        "FURNITURE": [
                            "沙发"
                        ],
                        "HOTWORDS": [],
                        "IDT": [],
                        "LOC": [],
                        "MNY": [],
                        "MSC": [
                            "沙发"
                        ],
                        "NEG": [],
                        "NUM": [],
                        "OFFENSIVE": [],
                        "ORG": [],
                        "PCT": [],
                        "PDT": [
                            "沙发"
                        ],
                        "PER": [],
                        "PROVINCE": [],
                        "SST": [],
                        "TEL": [],
                        "TIME": [],
                        "TIMES_NUM": [
                            1
                        ]
                    },
                    "pro": 0,
                    "sc": False,
                    "sentence": "清扫沙发底",
                    "tagword": [],
                    "user_action": [
                        "other"
                    ]
                }
            },
            {
                "in": {
                    "dm_transaction_id": "27063f24-b34a-4080-80eb-4f7d2740b21e",
                    "from": "deebot",
                    "qtime": 1727000934.8915179,
                    "sentence": "START_CLEAN",
                    "type": "event"
                },
                "out": {
                    "answer": {
                        "answer": "开始清洁",
                        "atime": 1727000935.132556,
                        "audio": "",
                        "audio_id": "START_CLEAN",
                        "available_inputs": [],
                        "callback": {},
                        "command": [],
                        "customize_msg": None,
                        "department_id": "553a10a8-317e-4630-87bf-314ab5352fa3",
                        "entities": [],
                        "group": "",
                        "instruction": "None",
                        "instruction_id": "6698b1e347f609707ac71134",
                        "intent": "START_CLEAN",
                        "join_answer": [],
                        "knowledgebase": "kb240718b0",
                        "label": "START_CLEAN",
                        "language": "zh-CN",
                        "listeningTime": -1,
                        "multiple_intents_replies": [],
                        "no_answer": False,
                        "offline": True,
                        "score": 2,
                        "send_to_client": True,
                        "sentence": "START_CLEAN",
                        "sim_query": "START_CLEAN",
                        "source": "intentqa",
                        "suggests": [],
                        "type": "business",
                        "voice": "开始清洁"
                    }
                },
                "prep": {
                    "answer_type": [],
                    "confidence": {
                        "answer_type": 1,
                        "emo": 1,
                        "pro": 1,
                        "user_action": 1
                    },
                    "emo": [
                        "neutral"
                    ],
                    "keyword": [],
                    "ner": {
                        "HOTWORDS": [],
                        "SST": []
                    },
                    "pro": 1,
                    "sentence": "START_CLEAN",
                    "tagword": [],
                    "user_action": [
                        "other"
                    ]
                }
            },
            {
                "in": {
                    "dm_transaction_id": "99431fcb-cccb-4222-9268-2159c284681f",
                    "from": "deebot",
                    "qtime": 1727000935.8570557,
                    "sentence": "event_wakeup_bypass",
                    "type": "event"
                },
                "out": {
                    "answer": {
                        "answer": "，",
                        "atime": 1727000936.083405,
                        "audio": "",
                        "audio_id": "",
                        "available_inputs": [],
                        "callback": {},
                        "command": [],
                        "customize_msg": None,
                        "department_id": "553a10a8-317e-4630-87bf-314ab5352fa3",
                        "entities": [],
                        "group": "",
                        "instruction": "None",
                        "instruction_id": "656fe336489a6bc9579d3dce",
                        "intent": "event_wakeup_bypass",
                        "join_answer": [],
                        "knowledgebase": "kb230621b0",
                        "label": "event_wakeup_bypass",
                        "language": "zh-CN",
                        "listeningTime": -1,
                        "multiple_intents_replies": [],
                        "no_answer": False,
                        "offline": False,
                        "score": 2,
                        "send_to_client": False,
                        "sentence": "event_wakeup_bypass",
                        "sim_query": "event_wakeup_bypass",
                        "source": "intentqa",
                        "suggests": [],
                        "type": "business",
                        "voice": "."
                    }
                },
                "prep": {
                    "answer_type": [],
                    "confidence": {
                        "answer_type": 1,
                        "emo": 1,
                        "pro": 1,
                        "user_action": 1
                    },
                    "emo": [
                        "neutral"
                    ],
                    "keyword": [],
                    "ner": {
                        "HOTWORDS": [],
                        "SST": []
                    },
                    "pro": 1,
                    "sentence": "event_wakeup_bypass",
                    "tagword": [],
                    "user_action": [
                        "other"
                    ]
                }
            },
            {
                "in": {
                    "dm_transaction_id": "233d1442-a151-468a-b143-201ff1c73c97",
                    "from": "deebot",
                    "qtime": 1727000941.7322679,
                    "sentence": "进行定制清洁",
                    "type": "text"
                },
                "out": {
                    "answer": {
                        "answer": "你好像还没有添加过该定制清洁，快去app的定制里添加吧",
                        "atime": 1727000941.9894633,
                        "audio": "",
                        "audio_id": "",
                        "available_inputs": [],
                        "callback": {},
                        "command": [],
                        "customize_msg": None,
                        "department_id": "553a10a8-317e-4630-87bf-314ab5352fa3",
                        "entities": [
                            "定制清洁",
                            "精细"
                        ],
                        "group": "",
                        "instruction": "定制清洁命令",
                        "instruction_id": "66e56511aae1ec2d9dc785e4",
                        "intent": "定制清洁",
                        "join_answer": [],
                        "knowledgebase": "kb240627b1",
                        "label": "",
                        "language": "zh-CN",
                        "listeningTime": None,
                        "multiple_intents_replies": [],
                        "no_answer": False,
                        "offline": False,
                        "score": 2,
                        "send_to_client": True,
                        "sentence": "进行定制清洁",
                        "sim_query": "定制清洁",
                        "source": "intentautomata",
                        "suggests": [],
                        "type": "business",
                        "voice": "你好像还没有添加过该定制清洁，快去app的定制里添加吧"
                    }
                },
                "prep": {
                    "answer_type": [
                        "其他"
                    ],
                    "confidence": {
                        "answer_type": 0.983741641,
                        "emo": 0.921824098,
                        "pro": 0.000682711601,
                        "user_action": 0.999864817
                    },
                    "emo": [
                        "neutral"
                    ],
                    "keyword": [
                        "精细",
                        "ng",
                        "定制",
                        "清洁"
                    ],
                    "ner": {
                        "BOK": [],
                        "CITY": [],
                        "DGT": [],
                        "DZQJ": [
                            "定制清洁"
                        ],
                        "GNCX": [
                            "定制清洁"
                        ],
                        "HOTWORDS": [],
                        "IDT": [],
                        "LEVEL": [
                            "精细"
                        ],
                        "LOC": [],
                        "MNY": [],
                        "MSC": [],
                        "NEG": [],
                        "NUM": [],
                        "OFFENSIVE": [],
                        "ORG": [],
                        "PCT": [],
                        "PDT": [],
                        "PER": [],
                        "PROVINCE": [],
                        "SST": [],
                        "TEL": [],
                        "TIME": []
                    },
                    "pro": 0,
                    "sc": True,
                    "sentence": "精细ng定制清洁",
                    "tagword": [],
                    "user_action": [
                        "other"
                    ]
                }
            }
        ],
        "current_mode": "默认模式",
        "custom_info": {
            "[$custom_info:AdviceAnswer$]": "",
            "[$custom_info:SCID$]": None,
            "[$custom_info:advice_point$]": None,
            "[$custom_info:advice_space_text$]": "",
            "[$custom_info:advice_space_value$]": "",
            "[$custom_info:answer_message$]": "",
            "[$custom_info:auto_clean_origin_sentence$]": "清扫沙发底",
            "[$custom_info:biz_home_kg$]": None,
            "[$custom_info:bot_info$]": None,
            "[$custom_info:content$]": None,
            "[$custom_info:custom_clean$]": None,
            "[$custom_info:did$]": None,
            "[$custom_info:error_message$]": "沙发",
            "[$custom_info:exist$]": None,
            "[$custom_info:getLifeSpan$]": "{\"ret\": \"ok\", \"resp\": {\"body\": {\"code\": 0, \"data\": [{\"left\": 86038, \"total\": 86400, \"type\": \"autoWater_cleaningFluid\"}, {\"left\": 17882, \"total\": 18000, \"type\": \"brush\"}, {\"left\": 100, \"total\": 100, \"type\": \"cleaningSolution\"}, {\"left\": 2882, \"total\": 3000, \"type\": \"dustBag\"}, {\"left\": 30000, \"total\": 30000, \"type\": \"handFilter\"}, {\"left\": 7082, \"total\": 7200, \"type\": \"heap\"}, {\"left\": 8955, \"total\": 9000, \"type\": \"roundMop\"}, {\"left\": 8862, \"total\": 9000, \"type\": \"sideBrush\"}, {\"left\": 1757, \"total\": 1800, \"type\": \"strainer\"}, {\"left\": 1662, \"total\": 1800, \"type\": \"unitCare\"}], \"msg\": \"ok\"}, \"header\": {\"fwVer\": \"1.46.3\", \"hwVer\": \"0.1.1\", \"pri\": 1, \"ts\": \"1726998604718\", \"tzm\": 480, \"ver\": \"0.0.1\", \"wkVer\": \"0.1.54\"}}, \"id\": \"ZYpB\", \"payloadType\": \"j\"}",
            "[$custom_info:getVoiceAssistantState_lifeRemind$]": 1,
            "[$custom_info:getpushpartspartsmaterialNo$]": "110-2228-0001",
            "[$custom_info:is_replaced$]": None,
            "[$custom_info:llm_switch$]": "on",
            "[$custom_info:many_entity$]": 0,
            "[$custom_info:map_id$]": None,
            "[$custom_info:mode$]": "only_sweep",
            "[$custom_info:othernlu$]": None,
            "[$custom_info:point$]": None,
            "[$custom_info:qtcj$]": None,
            "[$custom_info:replaced_records$]": None,
            "[$custom_info:robot_model$]": None,
            "[$custom_info:scene$]": None,
            "[$custom_info:sound_volume$]": None,
            "[$custom_info:space_text$]": None,
            "[$custom_info:space_value$]": None,
            "[$custom_info:space_voice$]": "",
            "[$custom_info:times$]": None,
            "[$custom_info:times_num$]": None,
            "[$custom_info:trailing_audio_flag$]": 2,
            "[$custom_info:wakeup_word$]": None
        },
        "custom_info_expired": {
            "[$custom_info:AdviceAnswer$]": 1727000949.6126366,
            "[$custom_info:SCID$]": 0,
            "[$custom_info:advice_point$]": 1727000949.61264,
            "[$custom_info:advice_space_text$]": 1727000949.612642,
            "[$custom_info:advice_space_value$]": 1727000949.6126382,
            "[$custom_info:answer_message$]": 1727000949.6126087,
            "[$custom_info:auto_clean_origin_sentence$]": 1727000974.6126242,
            "[$custom_info:biz_home_kg$]": 0,
            "[$custom_info:bot_info$]": 0,
            "[$custom_info:content$]": 0,
            "[$custom_info:custom_clean$]": 1727000949.984478,
            "[$custom_info:did$]": 0,
            "[$custom_info:error_message$]": 1727000949.6126122,
            "[$custom_info:exist$]": 0,
            "[$custom_info:getLifeSpan$]": 1727013007.027858,
            "[$custom_info:getVoiceAssistantState_lifeRemind$]": 1727013007.0278597,
            "[$custom_info:getpushpartspartsmaterialNo$]": 1727086827.2594085,
            "[$custom_info:is_replaced$]": 0,
            "[$custom_info:llm_switch$]": 1727006925.0225282,
            "[$custom_info:many_entity$]": 1727000949.6126223,
            "[$custom_info:map_id$]": 0,
            "[$custom_info:mode$]": 1727000949.6125722,
            "[$custom_info:othernlu$]": 0,
            "[$custom_info:point$]": 0,
            "[$custom_info:qtcj$]": 0,
            "[$custom_info:replaced_records$]": 0,
            "[$custom_info:robot_model$]": 0,
            "[$custom_info:scene$]": 1727000949.612644,
            "[$custom_info:sound_volume$]": 0,
            "[$custom_info:space_text$]": 0,
            "[$custom_info:space_value$]": 0,
            "[$custom_info:space_voice$]": 1727000949.612567,
            "[$custom_info:times$]": 1727000949.6126142,
            "[$custom_info:times_num$]": 0,
            "[$custom_info:trailing_audio_flag$]": 1727000961.9986885,
            "[$custom_info:wakeup_word$]": 1727000457.2594104
        },
        "dialogue_current_count": 29,
        "dialogue_last_time": 1727000941.9991634,
        "dialogue_start_time": 1726998605.971603,
        "last_automata_traceroute_time": 1727000941.9850683,
        "last_route": {},
        "machine_state": "root",
        "suggest_state": "root",
        "user_id": "c70dbafe-7c0d-4294-9af4-17fee6cf8a56"
    }}
    r = rw_lock.set_parameter_20230904(dict_data, data, other_config)
    print(r, type(r))
